// app.ts
import { getLogger } from "./utils/logger";
import { setLogger as setOTALogger } from "./jl_lib/jl-ota/jl_ota_2.1.0";
import { setLogger as setRCSPLogger } from "./jl_lib/jl-rcsp/jl_rcsp_watch_1.1.0";
import { setLogger as setAppLogger } from "./utils/log";
import { RCSPManager } from "./lib/rcsp-impl/rcsp";
import { BleDataHandler, BleSendDataHandler } from "./lib/ble-data-handler";
import { UUID_NOTIFY, UUID_SERVICE, UUID_WRITE, wxBluetooth } from "./lib/rcsp-impl/bluetooth";
import { DeviceBluetooth, DeviceManager, DeviceHistory, DeviceReconnect } from "./lib/rcsp-impl/dev-bluetooth";
import api from "./api/index";
import { authManager } from "./api/auth-manager";

App<IAppOption>({
  globalData: {
      // 添加照片编辑器需要的设备信息
      myDevice: null,
      // 添加来源检测
      launchScene: null,
      referrerInfo: null,
      fromOfficialAccount: false
  } as any, 
  onLaunch(options?: WechatMiniprogram.App.LaunchShowOption) {
    console.log('[App] 小程序启动:', options);
    
    // 🎯 简化：只记录基本信息，不做复杂检测
    if (options) {
      this.globalData.launchScene = options.scene;
      this.globalData.referrerInfo = options.referrerInfo;
      console.log('[App] 📱 启动场景值:', options.scene);
    }
    
    // 获取设备信息，用于照片编辑器的尺寸计算
    // 注意: wx.getSystemInfoSync已废弃，建议后续升级为新API
    this.globalData.myDevice = wx.getSystemInfoSync()
    // wx.openBluetoothAdapter({
    //   success(res) {
    //     console.log("onLoad_openBluetoothAdapter", res);
    //   },
    //   fail(err) {  
    //     console.log("onLoad_openBluetoothAdapter", err);
    //   },
    //   complete() { },
    // });
    //打印设置
    const logger = getLogger()
    if (logger != null) {
      setOTALogger(logger)
      setRCSPLogger(logger)
      setAppLogger(logger)
    }
    
    {
      //蓝牙
      const bluetooth = wxBluetooth
      // bluetooth.bluetoothManager.openBluetoothAdapter()
      //RCSP协议
      RCSPManager.init({
        sendData: (deviceId, data) => {
          return BleSendDataHandler.sendData(deviceId, UUID_SERVICE, UUID_WRITE, data)
        }, getBleConnect: () => {
          return bluetooth.bleConnect
        }, getBleScan: () => {
          return bluetooth.bleScan
        }
      })
      //设备管理
      const bluetoothOption = new DeviceBluetooth.BluetoothOption()
      bluetoothOption.isUseMultiDevice = true
      bluetoothOption.bleScanStrategy = 0
      DeviceManager.init({
        bluetoothOption,
        iScan: bluetooth.bleScan,
        iConnect: bluetooth.bleConnect
      }).observe((event: any) => {
        switch (event.type) {
          case 'onBleDataBlockChanged'://调整mtu成功
            const eventInfo = event.onBleDataBlockChangedEvent
            if (eventInfo && eventInfo.status == 0) {
              BleSendDataHandler.setMtu(eventInfo.device.deviceId, eventInfo.block)
            }
            break;
          case 'onShowDialog'://弹窗
            // const onShowDialogEvent = event.onShowDialogEvent
            // ProductCache.onPopupDialog({ message: onShowDialogEvent.bleScanMessage })
            break;
          default:
            break;
        }
      })
      //蓝牙收数据
      const bleDataCallback = {
        onReceiveData: (res: WechatMiniprogram.OnBLECharacteristicValueChangeListenerResult) => {
          if (res.characteristicId.toLowerCase() === UUID_NOTIFY.toLowerCase() && res.serviceId.toLowerCase() === UUID_SERVICE.toLowerCase()) {
            RCSPManager.onReceiveData(res.deviceId, res.value)
          }
        }
      }
      BleDataHandler.init()
      BleDataHandler.addCallbacks(bleDataCallback)
      
      // 适配器兜底 + 自动回连
      const doReconnect = () => {
        try {
          const current = RCSPManager.getCurrentRcspOperateWrapper && RCSPManager.getCurrentRcspOperateWrapper()
          if (current && current.deviceId) {
            console.log('🔗 [AutoReconnect] 设备已连接，跳过重连:', current.deviceId)
            return
          }
          
          console.log('🔄 [AutoReconnect] 开始自动重连流程')
          
          // 策略3：lastDeviceId 兜底策略
          const tryFallbackStrategy = () => {
            const lastDeviceId = wx.getStorageSync('rcsp:lastDeviceId')
            if (lastDeviceId) {
              console.log('🆘 [AutoReconnect] 尝试兜底策略，使用lastDeviceId:', lastDeviceId)
              setTimeout(() => {
                try {
                  const cur = RCSPManager.getCurrentRcspOperateWrapper && RCSPManager.getCurrentRcspOperateWrapper()
                  if (!(cur && cur.deviceId)) {
                    const fakeDev = { deviceId: lastDeviceId, name: 'RCSP Device' } as any
                    DeviceManager.connecDevice && DeviceManager.connecDevice(fakeDev)
                  }
                } catch (e2) {
                  console.warn('❌ [AutoReconnect] 兜底策略失败:', e2)
                }
              }, 2000)
            } else {
              console.log('⚠️ [AutoReconnect] 无可用的重连策略')
            }
          }
          
          // 策略2：从服务器获取设备信息（如果已登录）
          const tryServerStrategy = () => {
            if (!authManager.isAuthenticated()) {
              console.log('🔐 [AutoReconnect] 用户未登录，跳过服务器策略，尝试兜底')
              setTimeout(() => tryFallbackStrategy(), 1000)
              return
            }
            
            console.log('🌐 [AutoReconnect] 尝试从服务器获取设备信息')
            api.getDevices().then((response: any) => {
              if (response?.data?.data && response.data.data.length > 0) {
                const device = response.data.data[0]
                if (device.deviceId) {
                  console.log('✅ [AutoReconnect] 从服务器获取到设备:', device.deviceId)
                  const fakeDev = { deviceId: device.deviceId, name: device.deviceName || 'RCSP Device' } as any
                  DeviceManager.connecDevice && DeviceManager.connecDevice(fakeDev)
                  return
                }
              }
              console.log('⚠️ [AutoReconnect] 服务器无设备信息，尝试兜底策略')
              setTimeout(() => tryFallbackStrategy(), 1000)
            }).catch((error: any) => {
              console.warn('❌ [AutoReconnect] 服务器获取设备失败:', error)
              setTimeout(() => tryFallbackStrategy(), 1000)
            })
          }
          
          // 策略执行状态追踪
          let strategyExecuted = false
          
          // 策略1：尝试本地缓存重连
          const records = DeviceHistory.getHistoryRecordList && DeviceHistory.getHistoryRecordList()
          if (records && records.length > 0) {
            const last = records[records.length - 1]
            if (last) {
              console.log('📱 [AutoReconnect] 尝试本地历史记录重连:', last.address)
              strategyExecuted = true
              DeviceReconnect.startReconnectDevByHistoryRecrod(last, {
                onReconnectSuccess: (deviceId) => {
                  console.log('✅ [AutoReconnect] 本地重连成功:', deviceId)
                },
                onReconnectFailed: () => {
                  console.log('❌ [AutoReconnect] 本地重连失败，尝试其他策略')
                  // 本地重连失败后，继续尝试其他策略
                  setTimeout(() => tryServerStrategy(), 1000)
                }
              })
              return
            }
          }
          
          // 如果没有本地记录，直接尝试服务器策略
          if (!strategyExecuted) {
            tryServerStrategy()
          }
          
        } catch (err) {
          console.warn('❌ [AutoReconnect] doReconnect 执行异常:', err)
        }
      }
      try {
        if (bluetooth && bluetooth.bluetoothManager && bluetooth.bluetoothManager.isBluetoothAdapterAvailable && !bluetooth.bluetoothManager.isBluetoothAdapterAvailable()) {
          bluetooth.bluetoothManager.openBluetoothAdapter({
            success: () => setTimeout(doReconnect, 200),
            fail: () => { /* ignore */ }
          })
        } else {
          doReconnect()
        }
      } catch (e) {
        console.warn('rcspAutoReconnect skipped:', e)
      }

      // 添加登录状态监听，登录成功后自动重连
      authManager.addAuthStateListener((isLoggedIn: boolean, user: any) => {
        if (isLoggedIn && user) {
          console.log('🔐 [AuthStateChange] 用户登录成功，触发自动重连')
          
          // 延迟执行重连，确保登录流程完成
          setTimeout(() => {
            try {
              // 检查是否已有设备连接
              const current = RCSPManager.getCurrentRcspOperateWrapper && RCSPManager.getCurrentRcspOperateWrapper()
              if (current && current.deviceId) {
                console.log('🔗 [AuthStateChange] 设备已连接，跳过重连:', current.deviceId)
                return
              }

              console.log('🔄 [AuthStateChange] 开始登录后自动重连流程')
              
              // 策略1：尝试从服务器获取设备信息重连
              api.getDevices().then((response: any) => {
                if (response?.data?.data && response.data.data.length > 0) {
                  const device = response.data.data[0]
                  if (device.deviceId) {
                    console.log('✅ [AuthStateChange] 从服务器获取到设备，开始连接:', device.deviceId)
                    
                    // 保存到本地存储，供后续重连使用
                    wx.setStorageSync('rcsp:lastDeviceId', device.deviceId)
                    
                    const fakeDev = { 
                      deviceId: device.deviceId, 
                      name: device.deviceName || 'RCSP Device',
                      address: device.macAddress || device.deviceId
                    } as any
                    
                    DeviceManager.connecDevice && DeviceManager.connecDevice(fakeDev)
                    return
                  }
                }
                
                // 策略2：尝试本地历史记录重连
                console.log('⚠️ [AuthStateChange] 服务器无设备信息，尝试本地历史记录')
                const records = DeviceHistory.getHistoryRecordList && DeviceHistory.getHistoryRecordList()
                if (records && records.length > 0) {
                  const last = records[records.length - 1]
                  if (last) {
                    console.log('📱 [AuthStateChange] 使用本地历史记录重连:', last.address)
                    DeviceReconnect.startReconnectDevByHistoryRecrod(last, {
                      onReconnectSuccess: (deviceId) => {
                        console.log('✅ [AuthStateChange] 本地重连成功:', deviceId)
                      },
                      onReconnectFailed: () => {
                        console.log('❌ [AuthStateChange] 本地重连失败')
                      }
                    })
                    return
                  }
                }
                
                // 策略3：lastDeviceId 兜底策略
                const lastDeviceId = wx.getStorageSync('rcsp:lastDeviceId')
                if (lastDeviceId) {
                  console.log('🆘 [AuthStateChange] 使用lastDeviceId兜底策略:', lastDeviceId)
                  const fakeDev = { deviceId: lastDeviceId, name: 'RCSP Device' } as any
                  DeviceManager.connecDevice && DeviceManager.connecDevice(fakeDev)
                } else {
                  console.log('⚠️ [AuthStateChange] 无可用的重连策略')
                }
                
              }).catch((error: any) => {
                console.warn('❌ [AuthStateChange] 服务器获取设备失败:', error)
                
                // 失败时尝试本地重连
                const records = DeviceHistory.getHistoryRecordList && DeviceHistory.getHistoryRecordList()
                if (records && records.length > 0) {
                  const last = records[records.length - 1]
                  if (last) {
                    console.log('📱 [AuthStateChange] 服务器失败，使用本地历史重连:', last.address)
                    DeviceReconnect.startReconnectDevByHistoryRecrod(last, {
                      onReconnectSuccess: (deviceId) => {
                        console.log('✅ [AuthStateChange] 本地重连成功:', deviceId)
                      },
                      onReconnectFailed: () => {
                        console.log('❌ [AuthStateChange] 本地重连失败')
                      }
                    })
                  }
                }
              })
              
            } catch (err) {
              console.warn('❌ [AuthStateChange] 登录后自动重连异常:', err)
            }
          }, 1000) // 延迟1秒，确保登录流程和页面跳转完成
        }
      })
    }
  },
  onShow() {
    // 进入前台后尝试自动回连
    try {
      const bluetooth = wxBluetooth
      const doReconnect = () => {
        try {
          const current = RCSPManager.getCurrentRcspOperateWrapper && RCSPManager.getCurrentRcspOperateWrapper()
          if (current && current.deviceId) {
            console.log('🔗 [App-Show] 设备已连接，跳过重连:', current.deviceId)
            return
          }
          
          console.log('🔄 [App-Show] 前台重连流程开始')
          
          // 策略3：lastDeviceId 兜底策略
          const tryFallbackStrategy = () => {
            const lastDeviceId = wx.getStorageSync('rcsp:lastDeviceId')
            if (lastDeviceId) {
              console.log('🆘 [App-Show] 尝试兜底策略，使用lastDeviceId:', lastDeviceId)
              setTimeout(() => {
                try {
                  const cur = RCSPManager.getCurrentRcspOperateWrapper && RCSPManager.getCurrentRcspOperateWrapper()
                  if (!(cur && cur.deviceId)) {
                    const fakeDev = { deviceId: lastDeviceId, name: 'RCSP Device' } as any
                    DeviceManager.connecDevice && DeviceManager.connecDevice(fakeDev)
                  }
                } catch (e2) {
                  console.warn('❌ [App-Show] 兜底策略失败:', e2)
                }
              }, 2000)
            } else {
              console.log('⚠️ [App-Show] 无可用的重连策略')
            }
          }
          
          // 策略2：从服务器获取设备信息（如果已登录）
          const tryServerStrategy = () => {
            if (!authManager.isAuthenticated()) {
              console.log('🔐 [App-Show] 用户未登录，跳过服务器策略，尝试兜底')
              setTimeout(() => tryFallbackStrategy(), 1000)
              return
            }
            
            console.log('🌐 [App-Show] 尝试从服务器获取设备信息')
            api.getDevices().then((response: any) => {
              if (response?.data?.data && response.data.data.length > 0) {
                const device = response.data.data[0]
                if (device.deviceId) {
                  console.log('✅ [App-Show] 从服务器获取到设备:', device.deviceId)
                  const fakeDev = { deviceId: device.deviceId, name: device.deviceName || 'RCSP Device' } as any
                  DeviceManager.connecDevice && DeviceManager.connecDevice(fakeDev)
                  return
                }
              }
              console.log('⚠️ [App-Show] 服务器无设备信息，尝试兜底策略')
              setTimeout(() => tryFallbackStrategy(), 1000)
            }).catch((error: any) => {
              console.warn('❌ [App-Show] 服务器获取设备失败:', error)
              setTimeout(() => tryFallbackStrategy(), 1000)
            })
          }
          
          // 策略执行状态追踪
          let strategyExecuted = false
          
          // 策略1：尝试本地缓存重连
          const records = DeviceHistory.getHistoryRecordList && DeviceHistory.getHistoryRecordList()
          if (records && records.length > 0) {
            const last = records[records.length - 1]
            if (last) {
              console.log('📱 [App-Show] 尝试本地历史记录重连:', last.address)
              strategyExecuted = true
              DeviceReconnect.startReconnectDevByHistoryRecrod(last, {
                onReconnectSuccess: (deviceId) => {
                  console.log('✅ [App-Show] 本地重连成功:', deviceId)
                },
                onReconnectFailed: () => {
                  console.log('❌ [App-Show] 本地重连失败，尝试其他策略')
                  setTimeout(() => tryServerStrategy(), 1000)
                }
              })
              return
            }
          }
          
          // 如果没有本地记录，直接尝试服务器策略
          if (!strategyExecuted) {
            tryServerStrategy()
          }
          
        } catch (err) {
          console.warn('❌ [App-Show] doReconnect 执行异常:', err)
        }
      }
      
      if (bluetooth && bluetooth.bluetoothManager && bluetooth.bluetoothManager.isBluetoothAdapterAvailable && !bluetooth.bluetoothManager.isBluetoothAdapterAvailable()) {
        bluetooth.bluetoothManager.openBluetoothAdapter({
          success: () => setTimeout(doReconnect, 200),
          fail: () => { /* ignore */ }
        })
      } else {
        doReconnect()
      }
    } catch (e) {
      console.warn('❌ [App-Show] 前台重连异常:', e)
    }
  },
})
